#include "drawserver.h"
#include "./ui_drawserver.h"

DrawServer::DrawServer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DrawServer)
{
    ui->setupUi(this);
    // 禁止对文本框中的内容进行操作
    ui->messageBox->setTextInteractionFlags(Qt::NoTextInteraction);
    // 设置文本框中的鼠标指针样式
    ui->messageBox->viewport()->setCursor(Qt::ArrowCursor);
    // 停用开始游戏按钮
    ui->startGameBtn->setEnabled(false);
    // 绑定按钮和槽函数
    connect(ui->startServerBtn, &QAbstractButton::clicked, this, &DrawServer::changeRoomSlot);
    connect(ui->startGameBtn, &QAbstractButton::clicked, this, &DrawServer::startGameSlot);
}

DrawServer::~DrawServer()
{
    delete ui;
}

void DrawServer::changeRoomSlot(bool checked)
{
    // 启动服务端
    if(checked)
    {
        drawServer = new TcpServer();
        // 用户上线
        connect(drawServer, &TcpServer::signalNewClient, this, &DrawServer::newClientSlot);
        // 收到新消息
        connect(drawServer, &TcpServer::singalNewMsg, this, &DrawServer::newMsgSlot);
        // 用户下线
        connect(drawServer, &TcpServer::signalClientDisconnected, this, &DrawServer::clientDisconnectedSlot);
        // 允许开始游戏
        connect(drawServer, &TcpServer::signalAllowToPlay, ui->startGameBtn, &QWidget::setEnabled);
        ui->messageBox->append(tr("服务端启动成功"));
        ui->startServerBtn->setText("关闭服务端");
//        while(true)
//        {
//            drawServer->callDelay(1);
//            qDebug() << drawServer->hasPendingConnections();
//        }
    }
    else {
        // 关闭服务端
        if (drawServer != nullptr) {
            drawServer->close();
            ui->messageBox->append(tr("服务端关闭成功"));
            ui->startServerBtn->setText("启动服务端");
        }
    }
}

void DrawServer::newClientSlot(const QString& clientInfo)
{
    // 向消息列表中添加消息
    ui->messageBox->append(clientInfo + tr(" 发起了连接"));
    // 更新界面中的在线用户数量
    char const onlineUserCount = drawServer->clientSocketList.size() + '0';
    ui->userNumberLabel->setText(tr("当前在线用户数：") + onlineUserCount);
    // qDebug() << drawServer->userNameList.at(drawServer->userNameList.size() - 1);
    TcpServer::callDelay(1);
    ui->messageBox->append(drawServer->userNameList.at(drawServer->userNameList.size() - 1) + tr(" 上线了"));
}

void DrawServer::clientDisconnectedSlot(int descriptor)
{
    // 向消息列表中添加消息
    ui->messageBox->append(drawServer->userNameList.at(descriptor) + tr(" 离开了"));
    QByteArray onlineUserCount = QString::number(drawServer->clientSocketList.size()).toUtf8();
    ui->userNumberLabel->setText(tr("当前在线用户数：") + onlineUserCount);
    // qDebug() << drawServer->clientSocketList.count();
    if(drawServer->clientSocketList.size() < 2 && drawServer->isGamePlaying)
        ui->messageBox->append("在线用户数量小于 2，游戏结束");
}

void DrawServer::startGameSlot()
{
    ui->startGameBtn->setEnabled(false);
    ui->messageBox->append("游戏已经开始");
    drawServer->startGameSlot();
}

void DrawServer::newMsgSlot(const QByteArray& msg)
{
    // qDebug() << msg;
}
